﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RestSharp;
using Newtonsoft.Json.Linq;
using Tradier.Models;

namespace Tradier
{
    public partial class Users : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var accessToken = Session["UserTradierAccessToken"];
            if (accessToken == null)
            {
                Response.Redirect("/login.aspx");
            }
            GetUsersBalance(accessToken.ToString());
        }

        private void GetUsersBalance(string accessToken)
        {
            try
            {
                var client = new RestClient("https://api.tradier.com");
                var request = new RestRequest("/v1/user/balances", Method.GET);

                request.AddHeader("Authorization", "Bearer " + accessToken);
                var result = (client.Execute(request).Content);
                var json = JObject.Parse(result);

                var accounts = CreateMapping(json);
                uxAccounts.DataSource = accounts;
                uxAccounts.DataBind();
            }
            catch
            {
            }
        }

        private List<UserBalanceModel> CreateMapping(JObject json)
        {
            var userBalances = new List<UserBalanceModel>();
            var accounts = json["accounts"]["account"];
            if (accounts.GetType().Name == "JArray")
            {
                foreach (JObject account in accounts)
                {
                    var balance = account["balances"];
                    var accountBalance = new UserBalanceModel()
                    {
                        AccountNumber = (string)balance["account_number"],
                        AccountType = (string)balance["account_type"],
                        ClosePl = (float)balance["close_pl"],
                        CurrentRequirement = (float)balance["current_requirement"],
                        Equity = (float)balance["equity"],
                        LongMarketValue = (float)balance["long_market_value"],
                        MarketValue = (float)balance["market_value"],
                        OpenPl = (float)balance["open_pl"],
                        OptionLongValue = (float)balance["option_long_value"],
                        OptionRequirement = (float)balance["option_requirement"],
                        OptionShortValue = (float)balance["option_short_value"],
                        PendingOrdersCount = (int)balance["pending_orders_count"],
                        ShortMarketValue = (float)balance["short_market_value"],
                        StockLongValue = (float)balance["stock_long_value"],
                        TotalCash = (float)balance["total_cash"],
                        TotalEquity = (float)balance["total_equity"],
                        UnclearedFunds = (float)balance["uncleared_funds"]
                    };
                    userBalances.Add(accountBalance);
                }
            }
            else
            {
                var balance = accounts["balances"];
                var accountBalance = new UserBalanceModel()
                {
                    AccountNumber = (string)balance["account_number"],
                    AccountType = (string)balance["account_type"],
                    ClosePl = (float)balance["close_pl"],
                    CurrentRequirement = (float)balance["current_requirement"],
                    Equity = (float)balance["equity"],
                    LongMarketValue = (float)balance["long_market_value"],
                    MarketValue = (float)balance["market_value"],
                    OpenPl = (float)balance["open_pl"],
                    OptionLongValue = (float)balance["option_long_value"],
                    OptionRequirement = (float)balance["option_requirement"],
                    OptionShortValue = (float)balance["option_short_value"],
                    PendingOrdersCount = (int)balance["pending_orders_count"],
                    ShortMarketValue = (float)balance["short_market_value"],
                    StockLongValue = (float)balance["stock_long_value"],
                    TotalCash = (float)balance["total_cash"],
                    TotalEquity = (float)balance["total_equity"],
                    UnclearedFunds = (float)balance["uncleared_funds"]
                };
                userBalances.Add(accountBalance);
            }

            return userBalances;
        }
    }
}